package com.hermes.comics.dialogs;

import android.app.Activity;
import android.app.ProgressDialog;

import android.content.Context;
import android.content.DialogInterface;

import android.widget.BaseAdapter;
import android.widget.Toast;

import com.hermes.comics.R;
import com.hermes.comics.data.Catalog;
import com.hermes.comics.data.Issue;
import com.hermes.comics.data.IssueTag;
import com.hermes.comics.data.Serie;
import com.hermes.comics.data.SerieTag;
import com.hermes.comics.extractors.WebExtractorBuilder;
import com.hermes.comics.extractors.WebExtractor;

import java.net.HttpURLConnection;

/**
 */
public class AutoUpdateSerieDialog extends RemoteCatalogDialog implements RemoteCatalogDialog.Interface {
   
  private final Serie serie;
  private final BaseAdapter adapter;

  private String urlForEdit = null;

  public AutoUpdateSerieDialog(Activity activity, Serie serie, BaseAdapter adapter) {
    super(activity);

    this.serie = serie;
    this.adapter = adapter;

    setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    setMax(2);
    setIndeterminate(false);
    setProgressNumberFormat("");
    setTitle(SerieTag.TITLE.value(serie));
    setMessage("Auto update...");
    setProgressNumberFormat("Fetching page...");
  }

  @Override
  public void onPreExecute() {
  }

  @Override
  public void onCancelled() {
    dismiss();
  }

  @Override
  public void onFailure(UrlWrapper result) {
    Toast.makeText(getContext(),
         "Error http status = " + result.httpStatus() + "\nMessage = " + result.message(), Toast.LENGTH_LONG).show();
    dismiss();
  }

  @Override
  public String getUrl() {
    Issue issue = serie.issues().get(0);
    return (urlForEdit == null) ? IssueTag.URL.value(issue) : urlForEdit;
  }

  @Override
  public void onSuccess(UrlWrapper url) {
    if (urlForEdit == null) {
      WebExtractor extractor = WebExtractorBuilder.build(url.url(), url.content());
      if (extractor == null) {
        abort();
        Toast.makeText(getContext(), "There's no extractor for url " + getUrl(), Toast.LENGTH_LONG).show();
        return;
      }

      if (!extractor.extractSerie(serie)) {
        Toast.makeText(getContext(), "Serie could not be extracted. Url = " + getUrl(), Toast.LENGTH_LONG).show();
        dismiss();
        return;
      }

      urlForEdit = serie.urlForEdit();

      incrementProgressBy(1);
      setProgressNumberFormat("Saving remotely...");

      execute(this);
    } else {
      Catalog.getInstance().commit(serie);
      dismiss();
      adapter.notifyDataSetChanged();
      adapter.notifyDataSetInvalidated();
    }
  }

  @Override
  public void show() {
    super.show();
    if (WebExtractorBuilder.canBuild(getUrl())) {
      execute(this);
    } else {
      dismiss();
      Toast.makeText(getContext(), "There's no extractor for url " + getUrl(), Toast.LENGTH_LONG).show();
    }
  }
}
